import java.util.ArrayList;
import java.util.List;

public class Pool {
    private int width;
    private int length;
    private final int DEFAULT_WIDTH = 1;
    private final int DEFAULT_LENGTH = 1;

    private AllCreatures allCreatures;

    public Pool(int width, int length, int victims, int predators, int obstacles) {
        if (width > 0) {
            this.width = width;
        } else {
            this.width = DEFAULT_WIDTH;
        }

        if (length > 0) {
            this.length = length;
        } else {
            this.length = DEFAULT_LENGTH;
        }
        if (victims > 0 && predators > 0 && obstacles > 0) {
            allCreatures = new AllCreatures(victims, predators, obstacles, width, length);
        }
    }

    public int getLength() {
        return length;
    }

    public int getWidth() {
        return width;
    }

    public void doCycle() {
        List<Fish> newFish = new ArrayList<Fish>();

        for (Fish fish : allCreatures) {
            if (!fish.isDead()){
                fish.grow();

                // TODO here can be infinity cycle, should check is there some possible steps.
                do {
                    fish.move(allCreatures.findNearestVictim(fish.getPosition(), fish.getMaxStep()));
                } while (allCreatures.isObstacleOnPosition(fish.getPosition()));

                if (fish.isTimeToSpawn()) {
                    newFish.add(fish.spawn());
                }

                //eat
                if (fish.canEat(allCreatures.isVictimOnPosition(fish.getPosition()))) {
                    Victim eatenVictim = allCreatures.firstVictimOnPosition(fish.getPosition());
                    eatenVictim.setEaten();
                    fish.eat();
                }
                fish.die();
            }
        }
        allCreatures.clear();
        for (Fish fish : newFish) {
            allCreatures.add(fish);
        }
    }

    public String toString() {
        String str = String.format("This is pool with width %d and length %d%n", width, length);
        str += allCreatures;
        return str;
    }

    public String getStatistic() {
        Statistic statistic = new Statistic(allCreatures);
        return statistic.toString();

    }
}
